<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <video src="" id="video"></video>
    <canvas id="canvas" width="300" height="300"> </canvas>
    <script>


        let canvas = document.querySelector("#canvas")
        let context = canvas.getContext("2d");
        function cameraStart() {
            let isFront = false;

            let config = {
                audio: false, video: true, video: {
                    width: 300,
                    height: 300,
                    facingMode: isFront ? "user" : "environment",
                    frameRate: { ideal: 30, max: 30 }
                },
            };
            let video = document.querySelector("#video")
            function successCallback(stream) {
                // 将返回的流提供给控制台进行检查
                console.log(stream)
                video.srcObject = stream;
                // 播放
                video.play();
            }
        
            // 传入3个参数，第一个是配置，第二个是成功的回调
            // 这个更加规范了，多加了一个mediaDevices。window.navigator.getUserMedia(config, successCallback, errorCallback);
            navigator.mediaDevices.getUserMedia(config)
                .then(function (stream) {
                    successCallback(stream)
                })
              
            video.oncanplay = function () {
                video.play();
                switchToCanvas();
            }
        }

        function switchToCanvas() {
            // 将video上的图片的每一帧以图片的形式绘制的canvas上
            context.drawImage(video, 0, 0, 300, 300);
            window.requestAnimationFrame(switchToCanvas);
        }
        // 调用
        cameraStart()


        function cosine_similarity(param_a, param_b, param_depth) {
            // 求点积
            console.log(param_a, param_b, param_depth)
            let plus_sum = 0;
            for (let i = 0; i < param_depth; i++) {
                let tempAB = param_a[i] * param_b[i];
                plus_sum += tempAB;
            }
            // 求 A 模长
            let paramA_temp_length = 0;
            for (let i = 0; i < param_depth; i++) {
                paramA_temp_length += Math.pow(param_a[i], 2);
            }
            let paramA_length = Math.pow(paramA_temp_length, 0.5);

            // 求 B 模长
            let paramB_temp_length = 0;
            for (let i = 0; i < param_depth; i++) {
                paramB_temp_length += Math.pow(param_b[i], 2);
            }
            let paramB_length = Math.pow(paramB_temp_length, 0.5);
            let result = plus_sum / (paramA_length * paramB_length);
            return result;
        }
    </script>
</body>

</html>